using System;
using Microsoft.SPOT.Hardware;
using ReefinDotNet;

namespace ReefinDotNet.i2c
{
    public class i2cBus
    {
        static I2CDevice device;
        I2CDevice.Configuration config;


        public i2cBus(I2CDevice.Configuration Config)
        {
            config = Config;

            if (device == null)
                device = new I2CDevice(config);
        }


        public Int32 Read(Byte[] ReadBuffer)
        {
            Int32 retVal = -1;

            lock (device)
            {
                device.Config = config;

                I2CDevice.I2CTransaction[] transaction = new I2CDevice.I2CTransaction[] 
                {
                    I2CDevice.CreateReadTransaction(ReadBuffer)
                };

                retVal = device.Execute(transaction, 100);
            }

            return retVal;
        }

        public Int32 ReadRegister(Byte Register, Byte[] ReadBuffer)
        {
            return WriteRead(new Byte[] { Register }, ReadBuffer);
        }


        public Int32 Write(Byte[] WriteBuffer)
        {
            Int32 retVal = -1;

            lock (device)
            {
                device.Config = config;

                I2CDevice.I2CTransaction[] transaction = new I2CDevice.I2CTransaction[]
                {
                    I2CDevice.CreateWriteTransaction(WriteBuffer)
                };

                retVal = device.Execute(transaction, 100);
            }

            return retVal;
        }

        public Int32 WriteRegister(Byte Register, Byte WriteBuffer)
        {
            Byte[] tmp = new Byte[2];

            tmp[0] = Register;
            tmp[1] = WriteBuffer;

            return Write(tmp);
        }

        public Int32 WriteRegister(Byte Register, Byte[] WriteBuffer)
        {
            Byte[] tmp = new Byte[WriteBuffer.Length + 1];

            tmp[0] = Register;
            WriteBuffer.CopyTo(tmp, 1);

            return Write(tmp);
        }


        public Int32 WriteRead(Byte[] WriteBuffer, Byte[] ReadBuffer)
        {
            Int32 retVal = -1;

            lock (device)
            {
                device.Config = config;

                I2CDevice.I2CTransaction[] transaction = new I2CDevice.I2CTransaction[]
                {
                    I2CDevice.CreateWriteTransaction(WriteBuffer),
                    I2CDevice.CreateReadTransaction(ReadBuffer)
                };

                retVal = device.Execute(transaction, 100);
            }

            return retVal;
        }


        public I2CDevice Device
        {
            get
            {
                return device;
            }
        }

        public I2CDevice.Configuration Config
        {
            get
            {
                return config;
            }
        }


    }
}
